#include "MovableObject.h"
#include "Graph.h"

MovableObject::MovableObject(void)
	: mpCurrentNode(NULL), mpTargetNode(NULL), mDistance(0), mDirection(Ogre::Vector3::ZERO), 
	  mRotationAxis(Ogre::Vector3::NEGATIVE_UNIT_Z), mSpeed(35.0f)
{
}

MovableObject::~MovableObject(void)
{
}

void MovableObject::setNode(PathNode* pNode)
{
	mpCurrentNode = pNode;

	if(mpCurrentNode != NULL)
		setPosition(pNode->getPosition());
}

bool MovableObject::moveToTarget(const Ogre::FrameEvent& evt)
{
	Ogre::Real move = mSpeed * evt.timeSinceLastFrame;
	mDistance -= move;

	if(mDistance > 0.0f)
	{
		mpNode->translate(mDirection * move);
	}

	return mDistance <= 0.0f;
}

void MovableObject::setRotationAxis(Ogre::Vector3 axis)
{
	mRotationAxis = axis;
}

void MovableObject::setSpeed(float speed)
{
	mSpeed = speed;
}

void MovableObject::setTarget(PathNode* pNode)
{
	//Snap to and save the current node
	setNode(mpTargetNode);
	mpTargetNode = pNode;

	mDirection = pNode->getPosition() - mpNode->getPosition();
	mDistance = mDirection.normalise();
		
	Ogre::Vector3 src = mpNode->getOrientation() * mRotationAxis;
	if((1.0f + src.dotProduct(mDirection)) < 0.0001f) 
	{
		mpNode->yaw(Ogre::Degree(180));
	}
	else
	{
		Ogre::Quaternion quat = src.getRotationTo(mDirection);
		mpNode->rotate(quat);
	}
}